package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.CommonConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.properties.ShopProperties;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private ShopProperties shopProperties;
    @Value("${sky.baidu.baidu-url}")
    private String baiduUrl;
    @Value("${sky.baidu.riding-url}")
    private String ridingUrl;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //判断收货地址为空、超出配送范围、购物车为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Long userId = BaseContext.getCurrentId();
        //查询当前用户的购物车数据
        ShoppingCart shoppingCart = ShoppingCart.
                builder()
                .userId(userId)
                .build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.listShoppingCart(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //优化用户下单功能，加入校验逻辑，如果用户的收货地址距离商家门店超出配送范围（配送范围为5公里内），则下单失败。
        if (!checkRange(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail())) {
            throw new OrderBusinessException(MessageConstant.OUTTRANGE);
        }

        //补全订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        order.setNumber(String.valueOf(System.currentTimeMillis())); //订单号
        order.setStatus(Orders.PENDING_PAYMENT);    //订单状态默认为1待付款
        order.setUserId(userId);    //用户id
        order.setUserName(userMapper.getUserById(userId).getName()); //用户名称
        order.setOrderTime(LocalDateTime.now());    //下单时间
        order.setPayStatus(Orders.UN_PAID); //支付状态默认为0未支付
        order.setPhone(addressBook.getPhone()); //收货人手机号码
        order.setAddress(addressBook.getDetail());  //收货人详细地址
        order.setConsignee(addressBook.getConsignee()); //收货人

        order.setTablewareNumber(ordersSubmitDTO.getTablewareNumber());
        order.setTablewareStatus(ordersSubmitDTO.getTablewareStatus());
        //向订单表插入数据
        ordersMapper.insert(order);

        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }
        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //根据userId删除购物车中的信息
        shoppingCartMapper.deleteShoppingCart(shoppingCart);

        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getUserById(userId);
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "小木外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);
        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);

        //用户下单并且支付成功后，第一时间通知外卖商家，使用WebSocket实现
        //构建json数据
        Map<Object, Object> map = new HashMap<>();
        map.put("type", CommonConstant.ORDER_REMINDER);//消息类型，1表示来单提醒
        map.put("orderId",orders.getId());
        map.put("content", "订单号：" + outTradeNo);
        //推送信息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 历史订单查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        //设置分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //分页条件查询
        Page<Orders> ordersPage = ordersMapper.listOrders(ordersPageQueryDTO);
        List<OrderVO> orderVOList = new ArrayList<>();

        if (ordersPage != null && ordersPage.getTotal() > 0) {
            for (Orders orders : ordersPage) {
                // 查询订单明细，根据order_id查询
                List<OrderDetail> orderDetails = orderDetailMapper.listOrderDetailsByOrderId(orders.getId());
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                orderVOList.add(orderVO);
            }
            return new PageResult(ordersPage.getTotal(), orderVOList);
        }
        return null;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {
        OrderVO orderVO = new OrderVO();
        //根据订单id查询订单信息
        Orders order = ordersMapper.getOrdersById(id);
        //根据orderId查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.listOrderDetailsByOrderId(order.getId());
        BeanUtils.copyProperties(order,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 取消订单
     */
    @Override
    public void userCancelById(Long id) {
        // 根据id查询订单
        Orders order = ordersMapper.getOrdersById(id);

        // 校验订单是否存在
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (order.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(order.getId());
        // 订单处于待接单状态下取消，需要进行退款
        if (order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口 --由于没有可用的商户id，下面的退款操作执行会失败，直接注释即可，假设退款成功了，直接修改状态
            // weChatPayUtil.refund(
            //         ordersDB.getNumber(), //商户订单号
            //         ordersDB.getNumber(), //商户退款单号
            //         new BigDecimal(0.01),//退款金额，单位 元
            //         new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id 订单id
     */
    @Override
    public void repetition(Long id) {
        //获取userId
        Long userId = BaseContext.getCurrentId();
        //根据订单id查询订单详情 返回多个数据
        List<OrderDetail> orderDetailList = orderDetailMapper.listOrderDetailsByOrderId(id);
        //遍历订单详情，存入多个购物车对象，确认唯一一个userId
        for (OrderDetail orderDetail : orderDetailList){
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            //补全userId
            shoppingCart.setUserId(userId);
            //补全createTime
            shoppingCart.setCreateTime(LocalDateTime.now());
            //将多个购物车存入购物车表
            shoppingCartMapper.insertShoppingCart(shoppingCart);
        }
    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //使用分页插件进行分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //得到全部的订单
        Page<Orders> ordersPage = ordersMapper.listOrders(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();
        //根据订单id得到订单详情
        List<Orders> ordersList = ordersPage.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                //菜品信息拼接成字符串赋值给OrderVO中的orderDishes属性
                //查询订单菜品详情信息（订单中的菜品和数量）
                List<OrderDetail> orderDetailList = orderDetailMapper.listOrderDetailsByOrderId(orders.getId());
                // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
                List<String> orderDishList = orderDetailList.stream().map(x -> {
                    String orderDish = x.getName() + "*" + x.getNumber() + ";";
                    return orderDish;
                }).collect(Collectors.toList());
                // 将该订单对应的所有菜品信息拼接在一起
                String orderDishes =  String.join("", orderDishList);
                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }

        return new PageResult(ordersPage.getTotal(),orderVOList);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(ordersMapper.countStatus(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setConfirmed(ordersMapper.countStatus(Orders.CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(ordersMapper.countStatus(Orders.DELIVERY_IN_PROGRESS));
        return orderStatisticsVO;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        //根据id查询订单
        Orders order = ordersMapper.getOrdersById(id);
        //根据订单id查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.listOrderDetailsByOrderId(order.getId());
        //存入OrderVO返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //将待接单的状态改成已接单
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        ordersMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据id查询订单
        Orders order = ordersMapper.getOrdersById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (order == null || !order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
//        Integer payStatus = order.getPayStatus();
//        if (payStatus.equals(Orders.PAID)) {
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    order.getNumber(),
//                    order.getNumber(),
//                    new BigDecimal("0.01"),
//                    new BigDecimal("0.01"));
//            log.info("申请退款：{}", refund);
//        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setId(order.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        ordersMapper.update(orders);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        //根据id查询订单
        Orders order = ordersMapper.getOrdersById(ordersCancelDTO.getId());
        //管理端取消订单需要退款，这里不实现

        //根据订单id更新订单状态为已取消、取消原因、取消时间
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id 订单id
     */
    @Override
    public void delivery(Long id) {
        // 根据id查询订单
        Orders order = ordersMapper.getOrdersById(id);

        // 校验订单是否存在，并且状态为3
        if (order == null || !order.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(order.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        ordersMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        // 根据id查询订单
        Orders order = ordersMapper.getOrdersById(id);

        // 校验订单是否存在，并且状态为4
        if (order == null || !order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(order.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        ordersMapper.update(orders);
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = ordersMapper.getOrdersById(id);
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //构建json数据
        Map<Object, Object> map = new HashMap<>();
        map.put("type", CommonConstant.REMINDER);//消息类型，2表示用户催单
        map.put("orderId",id);
        map.put("content", "订单号：" + orders.getNumber());
        //推送信息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 检测配送距离是否超出范围
     * @param address
     * @return
     */
    public boolean checkRange(String address){
        //店铺的经纬度
        Map<String, String> params = new LinkedHashMap<>();
        params.put("address", shopProperties.getAddress()); //店铺地址
        params.put("output", "json");   //输出格式为json
        params.put("ak", shopProperties.getAk());
        //得到对应的位置坐标
        String addressJson = HttpClientUtil.doGet(baiduUrl,params);
        //解析位置坐标得到店铺的经纬度的JSON串
        JSONObject jsonObject = JSON.parseObject(addressJson);//{result:location:lng,lat}

        if (!jsonObject.get("status").equals(0)) { //地址解析失败
            throw new OrderBusinessException(MessageConstant.ADDRESS_PARSE_FAILED);
        }

        //取得JSON串中的result中的经纬度坐标location
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        //经度值 float
        Object lng = location.get("lng");
        //纬度值 float
        Object lat = location.get("lat");
        //拼接店铺的纬经度
        String origin = lat + "," + lng;

        //外卖地址的经纬度
        Map<String, String> myParams = new LinkedHashMap<>();
        myParams.put("address",address); //店铺地址
        myParams.put("output", "json");   //输出格式为json
        myParams.put("ak", shopProperties.getAk());
        //得到对应的位置坐标
        String myAddressJson = HttpClientUtil.doGet(baiduUrl,myParams);
        //解析位置坐标得到店铺的经纬度的JSON串
        JSONObject myJsonObject = JSON.parseObject(myAddressJson);//{result:location:lng,lat}

        if (!myJsonObject.get("status").equals(0)) { //地址解析失败
            throw new OrderBusinessException(MessageConstant.ADDRESS_PARSE_FAILED);
        }

        //取得JSON串中的result中的经纬度坐标location
        JSONObject myLocation = myJsonObject.getJSONObject("result").getJSONObject("location");
        //经度值 float
        Object myLng = myLocation.get("lng");
        //纬度值 float
        Object myLat = myLocation.get("lat");
        //拼接外卖地址的纬经度
        String destination = myLat + "," + myLng;

        //计算相差的距离
        Map<String, String> lenMap = new LinkedHashMap<>();
        lenMap.put("origin",origin);
        lenMap.put("destination", destination);
        lenMap.put("ak", shopProperties.getAk());
        //得到两地之间的路线JSON字符串
        String lengthJson = HttpClientUtil.doGet(ridingUrl,lenMap);
        JSONObject jsonObjectLen = JSON.parseObject(lengthJson);
        //超出省了，直接解析失败
        if (!jsonObjectLen.get("status").equals(0)){
            throw new OrderBusinessException(MessageConstant.THE_DISTANCE_IS_TOO_FAR);
        }
        //得到路线JSON字符串中的routes
        JSONArray routes = jsonObjectLen.getJSONObject("result").getJSONArray("routes");
        //得到routes中的方案距离，单位：米
        Integer distance = (Integer) routes.getJSONObject(0).get("distance");
        log.info("两地之间的距离为{}米",distance);

        return distance <= shopProperties.getDistance();
    }
}
